"""
sendcloud api send mail by template
"""
import json

import requests

from app.config.settings import SENDCLOUD


class SendCloud:
    def __init__(self, **kwargs):
        if kwargs:
            self.api_key = kwargs.get('api_key')
            self.api_user = kwargs.get('api_user')
            self.api_url = kwargs.get('api_url')
            self.fromuser = kwargs.get('fromuser')
            self.fromname = kwargs.get('fromname')
        else:
            self.api_key = SENDCLOUD['api_key']
            self.api_user = SENDCLOUD['api_user']
            self.api_url = SENDCLOUD['api_url']
            self.fromuser = SENDCLOUD['fromuser']
            self.fromname = SENDCLOUD['fromname']

        self.simple_send_url = "https://api.sendcloud.net/apiv2/mail/send"

    def encode_args(self, args):
        """格式化自定义参数为字符串
        """
        dict_string_list = []
        for key, value in args.items():
            if isinstance(value, dict):
                dict_list = []
                for k, v in value.items():
                    encode_list = [str("'{}'".format(s)) for s in v]
                    list_str = "'{}'".format(k) +\
                               ':[{}]'.format(','.join(encode_list))
                    dict_list.append(list_str)
                value_str = '{' + ','.join(dict_list) + '}'
            else:
                value_str = str(value)
            dict_str = "'{}'".format(key) + ':' + value_str
            dict_string_list.append(dict_str)
        _args = '{' + ','.join(dict_string_list) + '}'

        return _args

    def sendmail(self, template_invoke_name, args, timeout=5):
        """
        调用sendcloud api发送模板邮件
        template_invoke_name: 模板名称
        args：自定义参数
        """
        # 去掉subject，使用模板中的subject
        params = {
            "apiUser": self.api_user,
            "apiKey": self.api_key,
            "from": self.fromuser,
            "fromName": self.fromname,
            "templateInvokeName": template_invoke_name,
            "xsmtpapi": json.dumps(args),
        }
        try:
            resp = requests.post(self.api_url, data=params, timeout=timeout)
            status = "fail"
            result = resp.json()
            if result.get("result") and result.get("statusCode") == 200:
                status = "success"
            result = resp.text
        except Exception as e:
            status = "fail"
            result = str(e)
        return status, result

    def simple_sendmail(self, to_user, subject, html, timeout=20):
        """
        调用sendcloud api发送普通邮件
        """
        params = {
            "apiUser": self.api_user,
            "apiKey": self.api_key,
            "to": to_user,
            "from": self.fromuser,
            "fromName": self.fromname,
            "subject": subject,
            "html": html,
        }
        r = requests.post(self.simple_send_url, data=params, timeout=timeout)
        result = r.json()
        if result.get("result") and result.get("statusCode") == 200:
            status = "success"
        else:
            status = "fail"
        return status, r.text


if __name__ == "__main__":
    import datetime

    # 测试将邮箱改为自己的邮箱进行测试
    username = 'wush2@knownsec.com'
    args = {
        'to': [username],
        'sub': {
            '%user%': ['wush2'],
            '%time%': ['2021-06-01'],
            '%num%': [2],
            '%num1%': [''],
            '%num2%': [1],
            '%domain_list%': ['']
        }
    }
    template_name = 'scanvmax_http_has_expire'
    sendcloud = SendCloud()
    res = sendcloud.sendmail(template_name, args)
    print(1)
